package com.jy.api.controller.clerk;

import com.jy.api.dao.OrderDao;
import com.jy.api.domain.*;
import com.jy.api.payReq.AllPayBaseResult;
import com.jy.api.service.AmountNotMatchException;
import com.jy.api.service.OrderService;
import com.jy.api.service.PaymentService;
import com.jy.api.service.ProductService;
import com.jy.api.signUpReq.pos.PaymentSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/6/23.
 */

@Slf4j
@RestController
@RequestMapping(value = "v1/clerk", produces = "application/json;charset=utf-8")
public class ClerkScanPayController {
    private OrderDao orderService;
    private PaymentService paymentService;
    @Autowired
    private OrderService service;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    ProductService productService;

    /**
     * 订单支付（这个是clerk端扫码支付）
     *
     * @param paymentId
     * @param paymentSignUpReq
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT, value = "/scanPayments/{paymentId}")
    public ResponseEntity addScanPayments(@Valid @PathVariable(name = "paymentId") String paymentId,
                                          @RequestBody PaymentSignUpReq paymentSignUpReq,
                                          BindingResult bindingResult,
                                          HttpServletRequest request) throws Exception {
        Order switchOrder = orderService.findOne(paymentSignUpReq.getOrderId());
        String code = redisTemplate.opsForValue().get(switchOrder.getStoreId()+"switch");
        if (code!=null && code.equals("TRUE")){
            return ResponseEntity.badRequest().body("交班中，请等待交班完成后进行点单");
        }
        if (switchOrder.getType().equals(OrderType.SALES)){
            List<String> strings = productService.judgeProductQty(switchOrder.getId());
            if (strings.size()>0){
                return ResponseEntity.badRequest().body("订单中含有库存数量不足的商品，请移除后进行支付。");
            }
        }

        if (!switchOrder.getStatus().equals(OrderStatus.INIT) && !switchOrder.getStatus().equals(OrderStatus.CANCELED)) {
            log.warn("The status of order:{} is {}, micro pay is not allowed.", switchOrder.getId(), switchOrder.getStatus());
            return ResponseEntity.badRequest().body("订单当前状态不允许进行支付，请返回主页重新下单！");
        }
        long value = redisTemplate.getExpire(switchOrder.getId());
        if (value>0){
            return ResponseEntity.badRequest().body("请"+value+"秒后进行支付");
        }
        redisTemplate.opsForValue().set(switchOrder.getId(), switchOrder.getId(), 5, TimeUnit.SECONDS);
        Map<String, Object> orderData = new HashMap<>();
        orderData.put("notes", paymentSignUpReq.getNotes());
        orderData.put("tableNo", paymentSignUpReq.getTableNo());
        service.patch(paymentSignUpReq.getOrderId(), orderData);

        if (paymentSignUpReq.getChannel().equals(PaymentChannel.PAYCARD)) {
            log.info("门店{} 订单号{} 内容{} 操作内容{}", switchOrder.getStoreId(),switchOrder.getId(),"支付开始",paymentSignUpReq);
            if (0 == switchOrder.getAmount()) {
                return ResponseEntity.badRequest().body("点单金额为0元，不允许进行在线支付");
            }
            AllPayBaseResult result = paymentService.microPay(paymentSignUpReq.getOrderId(), paymentSignUpReq.getAuthCode());
            if (result.isSuccess()) {
                Order order = orderService.findOne(paymentSignUpReq.getOrderId());
                return ResponseEntity.ok().body(order);
            } else if (result.isNeedQuery()) {
                log.info("门店{} 订单号{} 内容{} 操作内容{}", switchOrder.getStoreId(),switchOrder.getId(),"用户支付中，请稍后进行查询",result);
                return ResponseEntity.accepted().build();
            }  else if (result.isFailed()) {
                return ResponseEntity.badRequest().body("支付失败");
            } else {
                throw new RuntimeException("支付结果未知，请稍后到订单列表查看支付状态");
            }
        } else if (paymentSignUpReq.getChannel().equals(PaymentChannel.CASH) || paymentSignUpReq.getChannel().equals(PaymentChannel.ALIPAY_CASH) || paymentSignUpReq.getChannel().equals(PaymentChannel.WECHATPAY_CASH)) {
            try {
                paymentService.cashPay(paymentSignUpReq.getOrderId(), paymentSignUpReq.getAmount(), paymentSignUpReq.getChannel());
                Order order = orderService.findOne(paymentSignUpReq.getOrderId());
                return ResponseEntity.ok().body(order);
            } catch (AmountNotMatchException e) {
                return ResponseEntity.badRequest().body("支付金额与订单金额不匹配，请检查");
            }

        } else if (paymentSignUpReq.getChannel().equals(PaymentChannel.MEMBER)) {
            try {
                paymentService.memberPay(paymentSignUpReq.getOrderId(), paymentSignUpReq.getAmount());
                Order order = orderService.findOne(paymentSignUpReq.getOrderId());
                return ResponseEntity.ok().body(order);
            } catch (MemberAccountNotEnoughException e) {
                return ResponseEntity.badRequest().body("会员账户余额不足，请提醒顾客充值");
            } catch (AmountNotMatchException e) {
                return ResponseEntity.badRequest().body("支付金额与订单金额不匹配，请检查");
            }
        } else {
            return ResponseEntity.badRequest().body("未识别的支付方式：" + paymentSignUpReq.getChannel());
        }
    }

    @Autowired
    public void setOrderService(OrderDao orderService) {
        this.orderService = orderService;
    }

    @Autowired
    public void setPaymentService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}
